package com.wuzao.ObserverPattern.application;

import com.wuzao.ObserverPattern.base.Observer;
import com.wuzao.ObserverPattern.base.Subject;

import java.util.ArrayList;
import java.util.List;

public class WeatherSubject implements Subject {
    /**
     * 存储订阅者（观察者）
     */
    private final List<Observer> observerList;
    private WeatherData weatherData;

    public void setWeatherData(WeatherData weatherData) {
        this.weatherData = weatherData;
    }

    public WeatherSubject(){
        observerList = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observerList.indexOf(observer);
        if(i>=0) observerList.remove(i);
    }

    @Override
    public void notifyObservers() {
        for(Observer observer:observerList){
            observer.update(weatherData);
        }
    }
}
